package com.software.loginregister.adapter;


import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.software.loginregister.R;
import com.software.loginregister.entity.ChatMessage;

import java.util.ArrayList;
import java.util.List;

import io.noties.markwon.Markwon;
import android.graphics.Outline;

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHolder> {
    private List<ChatMessage> messages;
    private Context context;
    private Markwon markwon;  // 添加Markwon实例

    public ChatAdapter(Context context) {
        this.context = context;
        this.messages = new ArrayList<>();
        this.markwon = Markwon.create(context);  // 初始化Markwon
    }

    @NonNull
    @Override
    public ChatViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_chat_message, parent, false);
        return new ChatViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ChatViewHolder holder, int position) {
        ChatMessage message = messages.get(position);
        RelativeLayout.LayoutParams messageParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
        );
        if (message.isUser()) {
            // 设置消息文本
            holder.messageText.setText(message.getMessage());
            holder.messageText.setBackgroundResource(R.drawable.bg_user_message);

            // 设置头像布局参数
            RelativeLayout.LayoutParams avatarParams = new RelativeLayout.LayoutParams(
                    dpToPx(40),  // 增大头像尺寸
                    dpToPx(40)
            );
            avatarParams.addRule(RelativeLayout.ALIGN_PARENT_END);
            avatarParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);  // 确保头像在顶部对齐
            avatarParams.setMargins(0, dpToPx(8), dpToPx(16), 0);  // 添加合适的边距
            holder.avatar.setLayoutParams(avatarParams);

            messageParams.addRule(RelativeLayout.LEFT_OF, holder.avatar.getId());  // 消息在头像左侧
            messageParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);  // 顶部对齐
            messageParams.setMargins(dpToPx(60), dpToPx(8), dpToPx(8), dpToPx(8));  // 调整边距
            holder.messageText.setLayoutParams(messageParams);

            // 设置消息气泡最大宽度
            holder.messageText.setMaxWidth(dpToPx(240));  // 限制最大宽度

            // 设置文本内边距
            holder.messageText.setPadding(
                    dpToPx(12),  // 左内边距
                    dpToPx(8),   // 上内边距
                    dpToPx(12),  // 右内边距
                    dpToPx(8)    // 下内边距
            );

            // 加载用户头像
            String avatarUrl = message.getAvatarUrl();
            if (avatarUrl != null && !avatarUrl.isEmpty()) {
                Glide.with(context)
                        .load(avatarUrl)
                        .circleCrop()
                        .placeholder(R.drawable.ic_default_avatar)
                        .error(R.drawable.ic_default_avatar)
                        .into(holder.avatar);
            } else {
                holder.avatar.setImageResource(R.drawable.ic_default_avatar);
            }

            // 设置头像圆角效果
            holder.avatar.setOutlineProvider(new ViewOutlineProvider() {
                @Override
                public void getOutline(View view, Outline outline) {
                    outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(),
                            view.getWidth() / 2);
                }
            });
            holder.avatar.setClipToOutline(true);
        } else {
            // AI消息部分保持不变
            markwon.setMarkdown(holder.messageText, message.getMessage());
            holder.messageText.setBackgroundResource(R.drawable.bg_ai_message);
            RelativeLayout.LayoutParams avatarParams = new RelativeLayout.LayoutParams(
                    dpToPx(32),
                    dpToPx(32)
            );
            avatarParams.addRule(RelativeLayout.ALIGN_PARENT_START);
            holder.avatar.setLayoutParams(avatarParams);
            messageParams.addRule(RelativeLayout.END_OF, R.id.iv_avatars);
            messageParams.setMargins(dpToPx(10), 0, dpToPx(28), 0);
            holder.messageText.setLayoutParams(messageParams);
            holder.avatar.setImageResource(R.mipmap.ic_aicooking);
        }
        // 动画效果保持不变
        holder.avatar.setVisibility(View.VISIBLE);
        holder.itemView.setAlpha(0f);
        holder.itemView.setTranslationY(50f);
        holder.itemView.animate()
                .alpha(1f)
                .translationY(0f)
                .setDuration(300)
                .setInterpolator(new DecelerateInterpolator())
                .start();
        // AI头像呼吸动画保持不变
        if (!message.isUser()) {
            ObjectAnimator scaleX = ObjectAnimator.ofFloat(holder.avatar, "scaleX", 1f, 1.05f, 1f);
            ObjectAnimator scaleY = ObjectAnimator.ofFloat(holder.avatar, "scaleY", 1f, 1.05f, 1f);
            scaleX.setRepeatCount(ValueAnimator.INFINITE);
            scaleY.setRepeatCount(ValueAnimator.INFINITE);
            AnimatorSet animatorSet = new AnimatorSet();
            animatorSet.playTogether(scaleX, scaleY);
            animatorSet.setDuration(2000);
            animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
            animatorSet.start();
        }
    }
    private int dpToPx(int dp) {
        float density = context.getResources().getDisplayMetrics().density;
        return Math.round(dp * density);}

    static class ChatViewHolder extends RecyclerView.ViewHolder {
        RelativeLayout rootLayout;
        TextView messageText;
        ImageView avatar;
        ChatViewHolder(View itemView) {
            super(itemView);
            rootLayout = itemView.findViewById(R.id.root_layout);
            messageText = itemView.findViewById(R.id.tv_message);
            avatar = itemView.findViewById(R.id.iv_avatars);
        }
    }

    @Override
    public int getItemCount() {
        return messages.size();
    }

    // 在Activity中添加消息时传入用户头像URL
    public void addMessage(String message, boolean isUser, String userAvatarUrl) {
        ChatMessage chatMessage = new ChatMessage(message, isUser, userAvatarUrl);
        messages.add(chatMessage);
        notifyItemInserted(messages.size() - 1);
    }
    public void addMessage(ChatMessage message) {
        messages.add(message);
        notifyItemInserted(messages.size() - 1);
    }


    public void removeLastMessage() {
        if (!messages.isEmpty()) {
            messages.remove(messages.size() - 1);
            notifyItemRemoved(messages.size());
        }
    }

    public List<ChatMessage> getMessages() {
        return messages;
    }

    public void clearMessages() {
        messages.clear();
        notifyDataSetChanged();
    }
}